import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { executor } from '@/services/executor'
import type { ExecutionResult } from '@/types/workflow'

export const useExecutionStore = defineStore('execution', () => {
    const executingTasks = ref<Set<string>>(new Set())
    const executionResults = ref<Map<string, ExecutionResult>>(new Map())

    // 计算属性
    const isExecuting = computed(() => executingTasks.value.size > 0)

    // 执行工作流
    const executeWorkflow = async (
        workflowId: string,
        nodes: any[],
        edges: any[],
        params: Record<string, any>
    ) => {
        try {
            executingTasks.value.add(workflowId)
            const result = await executor.executeWorkflow(workflowId, nodes, edges, params)
            executionResults.value.set(workflowId, result)
            return result
        } finally {
            executingTasks.value.delete(workflowId)
        }
    }

    // 取消执行
    const cancelExecution = (workflowId: string) => {
        executor.cancelExecution(workflowId)
        executingTasks.value.delete(workflowId)
    }

    // 获取执行结果
    const getExecutionResult = (workflowId: string) => {
        return executionResults.value.get(workflowId)
    }

    // 清除执行结果
    const clearExecutionResult = (workflowId: string) => {
        executionResults.value.delete(workflowId)
    }

    // 清除所有执行结果
    const clearAllExecutionResults = () => {
        executionResults.value.clear()
    }

    return {
        executingTasks,
        executionResults,
        isExecuting,
        executeWorkflow,
        cancelExecution,
        getExecutionResult,
        clearExecutionResult,
        clearAllExecutionResults
    }
}) 